﻿using Com.Ctrip.Framework.Apollo;
using Consul;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Primitives;
using Repository.communal;
using Sell.Api.Read.Application.CommandHandlers.CustomerCommandHandler;
using Sell.Api.Read.Application.CommandHandlers.SalesManagementCommandHandlers;
using SqlSugar;
using System.Reflection;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

builder.Services.AddDbContext<MyDbContext>(options =>
                options.UseMySql(
                    builder.Configuration.GetValue<string>("kmh"),
                    new MySqlServerVersion(new Version(9, 4)) // ָ�� MySQL �汾
                )
            );
// ���� SqlSugar
builder.Services.AddScoped<ISqlSugarClient>(provider =>
{
    var connectionString = builder.Configuration.GetValue<string>("kmh");

    return new SqlSugarClient(new ConnectionConfig()
    {
        ConnectionString = connectionString,
        DbType = DbType.MySql,
        IsAutoCloseConnection = true,
        InitKeyType = InitKeyType.Attribute
    });
});

// ע�� MediatR��������ǰ���򼯺� Application ����
builder.Services.AddMediatR(cfg => {
    cfg.RegisterServicesFromAssembly(Assembly.GetExecutingAssembly());
    cfg.RegisterServicesFromAssembly(typeof(CustomerlistCommandHandlers).Assembly);
    cfg.RegisterServicesFromAssembly(typeof(SupplierlistCommandHandlers).Assembly);
    cfg.RegisterServicesFromAssembly(typeof(VerificationlistCommandHandlers).Assembly);
});


static void RegisterConsul()
{
    try
    {
        var consulClient = new ConsulClient(p => {
            p.Address = new Uri("http://115.190.167.248:8500");//主机ip:8500
        });
        // 2. 确保健康检查端点可访问
        var httpCheck = new AgentServiceCheck()
        {
            DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(5),
            Interval = TimeSpan.FromSeconds(10),
            HTTP = "http://101.37.25.1:8003/WeatherForecast", // 确认此端口服务是否运行,WeatherForecast是天气预报控制器，如果没有这个控制器可以手动创建一个
            Timeout = TimeSpan.FromSeconds(5)
        };
        // 3. 添加标签方便识别
        var registration = new AgentServiceRegistration()
        {
            Checks = new[] { httpCheck },
            ID = $"sellread-{Guid.NewGuid()}", // 更易读的ID
            Name = "sellread",                // 业务api名称,必须小写
            Address = "101.37.25.1",                   // 纯IP正确
            Port = 8003,                               // 端口与健康检查一致
            Tags = new[] { "dotnet-service" }           // 添加标签
        };

        // 4. 添加错误处理
        var result = consulClient.Agent.ServiceRegister(registration).Result;
        Console.WriteLine($"服务注册成功! Status: {result.StatusCode}");
    }
    catch (Exception ex)
    {
        Console.WriteLine($"Consul注册失败: {ex.Message}");
    }
}










builder.Configuration.AddApollo
    (builder.Configuration.GetSection("Apollo")).AddDefault().AddNamespace("systemread");

var app = builder.Build();
if (app.Configuration is IConfigurationRoot configurationRoot)
{
    ChangeToken.OnChange(
        () => configurationRoot.GetReloadToken(),
        () => Console.WriteLine($"配置已更新:{app.Configuration.GetValue<string>("kmh")}"));
}

RegisterConsul();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
   
}
app.UseSwagger();
app.UseSwaggerUI();

app.UseAuthorization();

app.MapControllers();

app.Run();